<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * controller untuk modul schedule
 *
 * @property users_model $users
 * @property course_model $courses
 * @author Eko Prasetyo<nir@nirleka.web.id>
 */
class schedule_con extends CI_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->library('flash_message');
		$this->load->helper('date');
		$this->load->model('schedule/users_model', 'users');
		$this->load->model('schedule/course_model', 'courses');
	}

	/**
	 * fungsi untuk deklarasi view biar g duplikat, g bs dipanggil di url
	 * @param String $data
	 * @param Array $content
	 */
	private function __declare_view($data = NULL, $content_view = NULL) {
		$url = "schedule/" . $content_view;
		$header = array(
			'title' => "ComLabs IT Course | " . $data['title'],
			'type' => $data['type']
		);
		$this->load->view("schedule/header_view", $header);
		$this->load->view($url, $data);
		$this->load->view("schedule/footer_view");
	}

	public function __check_login() {
		//check login
		if (!$this->session->userdata('logged_in')) {
			$this->flash_message->error('Please login to continue');
			redirect('schedule/schedule_con/login');
		}
	}

	function index() {
		$this->login();
	}

	function login() {
		if ($this->session->userdata('logged_in'))
			redirect('schedule/schedule_con/today');
		$data['title'] = 'Login form';
		$data['type'] = 'Login Page';
		$this->__declare_view($data, "form_login");
	}

	function login_process() {
		//persiapkan password
		$data = array(
			'username' => $this->input->post('username'),
			'log_password' => $this->input->post('password')
		);
		$id = $this->users->do_login($data);
	}

	function logout() {
		$this->__check_login();
		$this->session->sess_destroy();
		$this->session->sess_create();
		$this->flash_message->success('Logout Success');
		redirect('schedule');
	}

	function today() {
		$this->__check_login();
		$data['title'] = 'Today | ' . date("D, d F Y", strtotime('now'));
		;
		$data['type'] = 'Schedule';
		$data['courses'] = $this->courses->get_course_byday("now");
		$this->__declare_view($data, "course_byday_view");
	}

	function tomorrow() {
		$this->__check_login();
		$data['title'] = 'Tomorrow | ' . date("D, d F Y", strtotime("+24 hours"));
		$data['type'] = 'Schedule';
		$data['courses'] = $this->courses->get_course_byday("+24 hours");
		$this->__declare_view($data, "course_byday_view");
	}

	function course() {
		$this->__check_login();
		$data['title'] = 'Course List';
		$data['type'] = 'Schedule';
		$data['courses'] = $this->courses->get_all_course();
		$this->__declare_view($data, "course_view");
	}

	function detail($kode_course = NULL, $angkatan = NULL) {
		$this->__check_login();
		$data['title'] = 'Course Detail';
		$data['type'] = 'Schedule';
		if (!empty($kode_course))
			$data['courses'] = $this->courses->get_courses($kode_course, $angkatan);
		$this->__declare_view($data, "detail_view");
	}

	function role() {
		$this->__check_login();
		$data = array(
			'title' => 'Role',
			'type' => 'Schedule',
			'roles' => array(
				'kode_pelatihan' => '',
				'role' => '',
				'nama_pelatihan' => '',
				'angkatan' => ''
			),
			'daftar_role' => array()
		);
		$data['roles'] = $this->users->get_role();
		$this->__declare_view($data, "role_view");
	}

	function edit_role() {
		$this->__check_login();
		//inisialisasi data
		$data = array(
			'title' => 'Edit Role',
			'type' => 'Schedule',
			'courses' => array(),
			'request_role' => array(
				'kode_pelatihan' => '-',
				'nama_pelatihan' => '',
				'tahun_term' => array(),
			),
			'daftar_role' => array()
		);
		$exclude_kode_kul = array();

		$data['daftar_role'] = $this->db->select('nama_pelatihan, kode_pelatihan, role, tahun, term')
				->where('id_user', $this->session->userdata('id'))
				->from('request_role natural join pelatihan')
				->get()
				->result_array();

		if (!empty($data['daftar_role']))
		{
			foreach ($data['daftar_role'] as $row) {
				array_push($exclude_kode_kul, $row['kode_pelatihan'].'-'.$row['tahun'].'-'.$row['term']);
			}
		}

		$data['courses'] = $this->courses->get_course_for_role($exclude_kode_kul);


		//kode_pelatihan via post
		if (!empty($_POST['kode_pelatihan'])) {
			$data['request_role']['kode_pelatihan'] = $this->input->post('kode_pelatihan');
			//nama_pelatihan
			$tmp_nama_course = $this->db
							->select('nama_pelatihan')
							->from('pelatihan')
							->where('kode_pelatihan', $data['request_role']['kode_pelatihan'])
							->get()->row_array();
			if (!empty($tmp_nama_course))
				$data['request_role']['nama_pelatihan'] = $tmp_nama_course['nama_pelatihan'];

			//tahun-term
			$tmp_tahun_term = $this->courses->get_mengajar_kelas($data['request_role']['kode_pelatihan']);
			$data['request_role']['tahun_term'] = $tmp_tahun_term;

			if (!empty($tmp_tahun))
				$data['request_role'] = $tmp_tahun;
			if (!empty($tmp_term))
				$data['term'] = $tmp_term;
		}
		$this->__declare_view($data, "role_edit_view");
	}

	function delete_role($kode, $tahun, $term) {
		$this->__check_login();
		$this->db->where('term', $term)
				->where('id_user', $this->session->userdata('id'))
				->where('tahun', $tahun)
				->where('kode_pelatihan', $kode)
				->delete('request_role');
		$this->flash_message->success("Role deleted");
		redirect('schedule/schedule_con/edit_role');
	}

	function change_role($kode, $tahun, $term) {
		$this->__check_login();
		$data = array('role' => $this->input->post('role_change'));
		$this->db->where('term', $term)
				->where('id_user', $this->session->userdata('id'))
				->where('tahun', $tahun)
				->where('kode_pelatihan', $kode)
				->update('request_role', $data);
		$this->flash_message->success("Role changed");
		redirect('schedule/schedule_con/edit_role');
	}

	function update_role() {
		$this->__check_login();
		if (!empty($_POST['tahun_term']) && (!empty($_POST['role'])) && (!empty($_POST['button']))) {
			//hapus data lama

			$this->db->where('id_user', $this->session->userdata('id'))
					->where('kode_pelatihan', $this->input->post('kode_pelatihan'))
					->delete('request_role');

			$data_baru = array();

			$temp_term = $this->input->post('tahun_term');
			$temp = explode('-', $temp_term);

			$data_baru['id_user'] = $this->session->userdata('id');
			$data_baru['kode_pelatihan'] = $this->input->post('kode_pelatihan');
			$data_baru['tahun'] = $temp[0];
			$data_baru['term'] = $temp[1];
			$data_baru['role'] = $this->input->post('role');

			$this->db->set($data_baru)
					->insert('request_role');

			$this->flash_message->success("Role updated");
			$this->session->set_flashdata(array('kode_pelatihan' => $this->input->post('kode_pelatihan')));
		} else {
			$this->flash_message->error("Data tidak boleh kosong");
		}
//		} else if (!empty($_POST['tahun_term'])) {
//
//			$this->db->where('ID', $this->session->userdata('id'))
//					->delete('mengajar_kelas');
//
//			//role kosong && tahun tdk kosong
//			if (empty($_POST['tahun_term'])) {
//				$this->db
//						->where('kode_pelatihan', $this->input->post('kode_pelatihan'))
//						->delete('mengajar_kelas', $row);
//				$this->flash_message->info("Role deleted");
//				$this->session->set_flashdata(array('updated' => true));
//				$this->session->set_flashdata(array('kode_pelatihan' => $this->input->post('kode_pelatihan')));
//				echo "<pre>";
//				var_dump("Saasfasf");
//				die();
//				echo "</pre>";
//			} else {
//				//tahun tidak kosong
//				$data_baru = array();
//				$tmp_year_term = $this->input->post('tahun_term');
//				$tmp_roles = $this->db->select('id_role')->from('daftar_role')->get()->result_array();
//				//bangkitkan data baru
//				$j = 0;
//				$k = 0;
//				for ($i = 0; $i < count($tmp_year_term) * count($tmp_roles); $i++) {
//					$temp = explode('-', $tmp_year_term[$j]);
//					$data_baru[$i]['id'] = $this->session->userdata('id');
//					$data_baru[$i]['kode_pelatihan'] = $this->input->post('kode_pelatihan');
//					$data_baru[$i]['tahun'] = $temp[0];
//					$data_baru[$i]['term'] = $temp[1];
//					$data_baru[$i]['id_role'] = $tmp_roles[$k]['id_role'];
//					$k++;
//					$j++;
//					if ($j == count($tmp_year_term)) {
//						$j = 0;
//					}
//					if ($k == count($tmp_roles))
//						$k = 0;
//				}
//				foreach ($data_baru as $row) {
//					$this->db->set($row)
//							->insert('mengajar_kelas');
//				}
//				$this->flash_message->success("Role updated");
//				$this->session->set_flashdata(array('updated' => true));
//			}
//		} else {
//			$this->flash_message->error("Term must checked");
//			$this->session->set_flashdata(array('error' => true));
//		}
//		$this->session->set_flashdata(array('kode_pelatihan' => $this->input->post('kode_pelatihan')));
		redirect('schedule/schedule_con/edit_role');
	}

	function biodata() {
		$this->__check_login();
		$data = array(
			'title' => 'Biodata',
			'type' => 'Profile',
			'biodata' => $this->users->get_user_scheme()
		);
		if ($this->users->is_peserta_exist($this->session->userdata('id')))
			$data['biodata'] = $this->users->get_biodata($this->session->userdata('id'));
		$this->__declare_view($data, "biodata_view");
	}

	function edit_photo() {
		$data = array(
			'title' => "Edit Photo",
			'type' => 'Profile'
		);

		$this->__declare_view($data, "photo_edit_view");
	}

	function upload_foto() {
		if (strcmp($this->input->post('submit_foto'), 'upload') === 0) {
			$config['upload_path'] = './foto/';
			$config['file_name'] = $this->session->userdata('username');
			$config['allowed_types'] = 'gif|jpg|png';
			$config['max_size'] = '100';
			$config['max_width'] = '500';
			$config['max_heigh'] = '500';
			$oldfile = $this->session->userdata('foto');

			$this->load->library('upload', $config);

			//hapus file lama. File Default tidak dihapus
			if (strcmp('default.jpg', $this->upload->file_name) != 0) {
				$oldfile = $this->session->userdata('foto');
				$this->load->helper('file');
				$file = './foto/' . $oldfile;
				@unlink($file);
			}
			if ($this->upload->do_upload('upload_foto')) {
				$this->users->update_foto(array('foto' => $this->upload->file_name));
				$this->session->set_userdata('foto', $this->upload->file_name);
				$this->flash_message->success('Upload Foto Success');
			} else {
				if (strcmp('default.jpg', $this->upload->file_name) == 0)
					$this->flash_message->error("File Name default.jpg not allowed, choose other file or rename it");
				$this->flash_message->error($this->upload->display_errors("", ""));
			}
		}
		redirect('schedule/schedule_con/edit_biodata');
	}

	function edit_biodata() {
		$this->__check_login();

		$data = array(
			'title' => 'Edit Biodata',
			'type' => 'Profile',
			'biodata' => $this->users->get_user_scheme()
		);
		$data['biodata'] = $this->users->get_biodata($this->session->userdata('id'));
		if ($this->users->is_peserta_exist($this->session->userdata('id'))) {
			$arr = explode("-", $data['biodata']['TANGGAL_LAHIR'], 3);
			$data['biodata']['date'] = $arr[2];
			$data['biodata']['month'] = $arr[1];
			$data['biodata']['year'] = $arr[0];
		} else {
			//tidak ada data user di table peserta (null)
			$data['biodata']['date'] = NULL;
			$data['biodata']['month'] = NULL;
			$data['biodata']['year'] = NULL;
		}
		$this->__declare_view($data, "biodata_edit_view");
	}

	function update_biodata() {
		if ((strcmp($this->input->post('button'), 'Save') === 0)) {
			$this->load->library('form_validation');
			$rules = array(
				array(
					'field' => 'password',
					'label' => 'Password',
					'rules' => 'required|min_length[4]|max_length[45]|xss_clean'
				),
				array(
					'field' => 'email',
					'label' => 'Email',
					'rules' => 'required|valid_email|max_length[45]'
				),
				array(
					'field' => 'tempat_lahir',
					'label' => 'Tempat Lahir',
					'rules' => 'max_length[45]'
				),
				array(
					'field' => 'alamat',
					'label' => 'Address',
					'rules' => 'max_length[45]'
				),
				array(
					'field' => 'no_telp',
					'label' => 'Telephone',
					'rules' => 'max_length[45]'
				)
			);
			$this->form_validation->set_rules($rules);
			if ($this->form_validation->run()) {
				$newdata = $this->input->post();
				$newdata['tanggal_lahir'] = $newdata['year'] . "-" . $newdata['month'] . "-" . $newdata['date'];
				unset($newdata['year']);
				unset($newdata['month']);
				unset($newdata['date']);
				unset($newdata['button']);
				array_values($newdata);
				$this->users->update_biodata($newdata);
			} else {
				//populate error
				$error = explode("-", validation_errors("-", " "));
				for ($i = 1; $i < sizeof($error); $i++) {
					print_r($error[$i]);
					$this->flash_message->error($error[$i]);
				}
			}
		}else
			$this->flash_message->info('No data inputed, data did not update');
		redirect('schedule/schedule_con/edit_biodata');
	}

}

//end of file
